package com.chey.service.impl;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author JanYao
 * @version 0.1
 */
@Service
public class VerifyServiceImpl implements com.chey.service.VerifyService{
    @Override
    public String verifyCode(String code) {
        String apiUrl = "https://api.resend.com/emails";
        String requestBody = "{\"from\": \"onboarding@resend.dev\",\"to\": \"janyao520@163.com\",\"subject\": \"欢迎注册航班管理平台\",\"html\": \"<p>Congrats on sending your <strong>"+code+"</strong>!</p>\"}";
        StringBuilder response = null;
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer re_RSybXTFz_FPAJBL2xbFbFdKryZY9hEE7p");
            connection.setDoOutput(true);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestBody.getBytes());
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                 response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();

                System.out.println("Email sent successfully: " + response.toString());

            } else {
                System.out.println("Error sending email. Response Code: " + responseCode);

            }

            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
      return response.toString();
    }
}
